package com.ocom.payhandle.controller;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.card.EntityXfDeviceInfo;
import com.ocom.common.entity.card.EntityXfGoodListOrg;
import com.ocom.common.entity.card.EntityXfGoodsListProcess;
import com.ocom.common.entity.payconfig.EntityDishesPrice;
import com.ocom.common.entity.payconfig.EntityDishesWhite;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.pyhandle.MenuListVo;
import com.ocom.common.vo.pyhandle.MenuPrice;
import com.ocom.common.vo.pyhandle.MenuPriceListVo;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.service.DeviceInfoService;
import com.ocom.payhandle.service.DishesPriceService;
import com.ocom.payhandle.service.DishesWhiteService;
import com.ocom.payhandle.service.XfGoodsListProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 2.11菜品白名单
 * @Author: 朱晖
 * @Date: 2022/12/29
 **/
@Slf4j
@RestController
public class DishesController {

	@Autowired
	private XfRecordFeign xfRecordFeign;

	@Autowired
	private DeviceInfoService deviceInfoService;

	@Autowired
	private DishesWhiteService dishesWhiteService;

	@Autowired
	private DishesPriceService dishesPriceService;

	@Autowired
	private XfGoodsListProcessService xfGoodsListProcessService;

	//2.11.1 获取菜品白名单（getDishesWhiteList）
	@PostMapping(PayHandleUrl.URL_getDishesWhiteList)
	public Result getDishesWhiteList(Long companyId, String machNo
			, @RequestParam(required = false, defaultValue = "10") Integer listLimit) {

		//1、从设备信息表xf_device_info找到com_id ，device_no匹配的记录deviceInfo。
		EntityXfDeviceInfo entityXfDeviceInfo = deviceInfoService.GetDeviceInfo(companyId, machNo);
		if (entityXfDeviceInfo == null) {
			return ResultUtil.error(ResultEnum.Err_4008);
		}

		Map<String, Object> resMap = new HashMap<>();
		resMap.put("list", new ArrayList<>());

		Integer menuDelete = entityXfDeviceInfo.getMenuDelete();

		//2、如果deviceInfo.menu_add == -1（全量）：
		if (entityXfDeviceInfo.getMenuAdd() == -1) {
			EntityDishesWhite entityDishesWhite = dishesWhiteService.getMaxId(companyId, entityXfDeviceInfo.getMenuMerchId());
			if (entityDishesWhite == null) {
				deviceInfoService.updateMenu(companyId, machNo,
						null,
						null,
						null,
						0
				);
				menuDelete = 0;
			}
			resMap.put("model", 0);
		}else{
			resMap.put("model", 1);
		}

		//3、从菜品白名单dishes_white查找满足条件的菜品dishesList：
		List<MenuListVo> dishesList = dishesWhiteService.dishesList(companyId,
				entityXfDeviceInfo.getMenuAdd(),
				entityXfDeviceInfo.getMenuDelete(),
				listLimit,
				entityXfDeviceInfo.getMenuMerchId()
		);
		if (dishesList == null || dishesList.size() == 0) {
			if (entityXfDeviceInfo.getMenuAdd() < 0) {
				deviceInfoService.updateMenu(companyId, machNo,
						2,
						null,
						0,
						menuDelete
				);
			} else {
				deviceInfoService.updateMenu(companyId, machNo,
						2,
						null,
						null,
						null);
			}
			return ResultUtil.success(resMap);
		} else {

			//如果dishesList不为空：menuTab := dishesList最后一条记录的dishesList.id。
			Integer menuTab = dishesList.get(dishesList.size()-1).getId();
			//4、把dishesList.dishes_id拼接成dishesIds（用逗号隔开）。
			//从菜品价格表dishes_price查找满足条件的价格pList：
			List<Integer> dishesIds = dishesList.stream().map(MenuListVo::getDishesId).collect(Collectors.toList());
			if (entityXfDeviceInfo.getPointId() == null) entityXfDeviceInfo.setPointId(0);
			List<EntityDishesPrice> priceList = dishesPriceService.selectDishesPriceList(companyId, entityXfDeviceInfo.getMenuMerchId(), entityXfDeviceInfo.getPointId(), dishesIds);

			//5、拼装菜单信息list：

			List<MenuPriceListVo> listVos = new ArrayList<>();
			for (MenuListVo menuListVo : dishesList) {
				MenuPriceListVo menuPriceListVo = new MenuPriceListVo();
				menuPriceListVo.setMenuNo(menuListVo.getDishesId());
				menuPriceListVo.setMenuCode(menuListVo.getDishesCode());
				menuPriceListVo.setMenuName(menuListVo.getDishesName());
				if (menuListVo.getState() == 0 && priceList != null && priceList.size() > 0) {
					for (EntityDishesPrice entityDishesPrice : priceList) {
						//找到pList.dishes_id = dishesList.dishes_id的记录；
						if (entityDishesPrice.getDishesId().equals(menuListVo.getDishesId())) {
							menuPriceListVo.getPriceList().add(new MenuPrice((int) entityDishesPrice.getPriceMode(),
									entityDishesPrice.getPrice()));
						}
					}
					//如果priceList为空
					if (menuPriceListVo.getPriceList().size() == 0) {
						menuPriceListVo.setFlag(2);
					} else {
						menuPriceListVo.setFlag(1);
					}
				} else {
					menuPriceListVo.setFlag(2);
				}
				listVos.add(menuPriceListVo);
			}

			resMap.put("list", listVos);

			deviceInfoService.updateMenu(companyId, machNo,
					null,
					null,
					menuTab,
					null
			);
			return ResultUtil.success(resMap);
		}
	}

	//2.11.2 更改菜品白名单状态（changeDishesWhiteState）
	@PostMapping(PayHandleUrl.URL_changeDishesWhiteState)
	public Result changeDishesWhiteState(Long companyId, String machNo) {
		//1、从设备信息表xf_device_info找到com_id ，device_no匹配的记录deviceInfo。
		EntityXfDeviceInfo entityXfDeviceInfo = deviceInfoService.GetDeviceInfo(companyId, machNo);
		if (entityXfDeviceInfo == null) {
			return ResultUtil.error(ResultEnum.Err_4008);
		}


		Map<String, Object> resMap = new HashMap<>();
		resMap.put("flag", 0);

		//2、如果deviceInfo.menu_state== 1:
		if(entityXfDeviceInfo.getMenuState()==1){
			deviceInfoService.updateMenu(companyId, machNo,
					null,
					entityXfDeviceInfo.getMenuAddTab(),
					null,
					null
			);
			resMap.put("flag", 255);
			return ResultUtil.success(resMap);
		}

		//3、如果deviceInfo.menu_state== 2：再查找一次有没有新的白名单：
		if(entityXfDeviceInfo.getMenuState()==2){
			EntityDishesWhite entityDishesWhite = dishesWhiteService.checkExist(companyId,entityXfDeviceInfo.getMenuMerchId(),
					entityXfDeviceInfo.getMenuAdd(),
					entityXfDeviceInfo.getMenuDelete());
			if(entityDishesWhite==null){
				deviceInfoService.updateMenu(companyId, machNo,
						entityXfDeviceInfo.getMenuAddTab()
				);
				resMap.put("flag", 0);
			}else{
				deviceInfoService.updateMenu(companyId, machNo,
						1,
						entityXfDeviceInfo.getMenuAddTab(),
						null,
						null
				);
				resMap.put("flag", 255);
			}
		}
		return ResultUtil.success(resMap);
	}

	@PostMapping(PayHandleUrl.URL_syncSaveGoodList)
	public Result syncSaveGoodList(Long comId, String orderNo){
		//查订单
		try {
			List<EntityXfGoodsListProcess> listProcesses =  xfGoodsListProcessService.getXfGoodsList(comId,orderNo);
			if(listProcesses!=null && listProcesses.size()>0){
				List<EntityXfGoodListOrg> listOrgs = JSON.parseArray(JSON.toJSONString(listProcesses),EntityXfGoodListOrg.class);
				for (EntityXfGoodListOrg entityXfGoodListOrg:listOrgs){
					entityXfGoodListOrg.setId(null);
					xfRecordFeign.saveXfGoodList(entityXfGoodListOrg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("消息-迁移订单详情表处理失败:【{}】",e);
		}
		return ResultUtil.success();
	}

}